dojo.require("dojo.parser");
dojo.require("dijit.layout.ContentPane");
dojo.require("dijit.layout.BorderContainer");
dojo.require("dijit.layout.TabContainer");
dojo.require("dojo.data.ItemFileReadStore");
dojo.require("dijit.tree.ForestStoreModel");
dojo.require("dijit.Tree");
dojo.require("dijit.Toolbar");
dojo.require("dijit.form.Button");
dojo.require("dojox.layout.FloatingPane");
dojo.require("dojox.fx");
dojo.require("dojox.layout.ExpandoPane");
dojo.require("dojox.image.Lightbox");
dojo.require("dijit.Tooltip");

dojo.addOnLoad(function() {
  //tablesDialog needs to be accessibile to the code further
  var tablesDialog;
  init();
});

function init() {
  //create the main tab
  var mainTab = new dijit.layout.ContentPane({ href: "preface.html",
                                                title: "Preface",
                                                id: "preface",
                                                onShow: onTabShow,
                                                onDownloadEnd: addDownloadLinkEventHandling,
                                                selected: true});
  tabContainer.addChild(mainTab);
  
  var preLoader = dojo.byId("preLoader");
	dojo.fadeOut({
		node: preLoader,
		duration: 720,
		onEnd: function(){
			dojo.style(preLoader,"display","none");
		}
	}).play();
  
  highlightNewNodes();  
  tablesDialog = new dojox.image.LightboxDialog({});
  tablesDialog.startup();
}

function addDownloadLinkEventHandling() {
  var downloadLink = dojo.byId("downloadlink");
  if (downloadLink) {
    dojo.connect(downloadLink, "onclick", function(event) {
      logAnalytics("Download");
      return true;
    });
  }
  
  var sourceLink = dojo.byId("sourcelink");
  if (sourceLink) {
    dojo.connect(sourceLink, "onclick", function(event) {
      logAnalytics("Sources");
      return true;
    });
  }
}

function highlightNewNodes() {
  topicStore.fetch({query: {isNew: true},
                    onComplete: onNewItemsFetch
                   });
}

function onNewItemsFetch(items) {
      var newDomNodes = new Array();
    dojo.forEach(items, function(itr) {
      var nodes = topicTree.getNodesByItem(itr);
      newDomNodes.push(dojo.byId(nodes[0].id));
    });
    new dijit.Tooltip({
            connectId: newDomNodes,
            label: "<b>Newly Added</b>",
            position : "left"
        });
}

function onNodeClick(item) {
  var topicType = topicStore.getValue(item, 'type');
  var haveChildren = topicStore.getValue(item, 'children');
  var topicId = topicStore.getIdentity(item);
  var topicLabel = topicStore.getLabel(item);
  var noToolbar = topicStore.getValue(item, 'noToolbar');
  if (topicType == "child" ||
      (topicType == "parent" &&  haveChildren == null)) {    
    var existingTab = dijit.byId(topicId);
    if(existingTab) {
      tabContainer.selectChild(existingTab);
      return;
    }
    
    //Create a BorderContainer, add toolbar to the top and contentpane to center
    var borderContainer = new dijit.layout.BorderContainer({  id: topicId,
                                                              title: topicLabel,
                                                              closable: true,
                                                              onClose: onTabClose,
                                                              onHide: onTabHide,
                                                              onShow: onTabShow
                                                           });
    if (!noToolbar)  {
      var toolbar = new dijit.Toolbar({region: "top"}, "toolbar");
      var sourceButton = new dijit.form.Button({
          id: topicId + "_src",
          label: "View Source",
          showLabel: true,
          onClick: onToolbarButtonClick
      });
      toolbar.addChild(sourceButton);
    
      var tablesButton = new dijit.form.Button({
          id: topicId + "_db",
          label: "View Table Structure",
          showLabel: true,
          onClick: onToolbarButtonClick
      });
      toolbar.addChild(tablesButton);
      borderContainer.addChild(toolbar);  
    }
    
    var centerPane = new dijit.layout.ContentPane({ href:topicId + ".html",
                                                    onDownloadEnd: highlightCode,
                                                    region:"center"});
    borderContainer.addChild(centerPane);
          
    tabContainer.addChild(borderContainer);
    tabContainer.selectChild(borderContainer);
  }
  
  logAnalytics(topicId);
}

function highlightCode() {
  SyntaxHighlighter.highlight(null, null);
}

function onToolbarButtonClick(event) {
  var buttonId = event.target.id;
  
  var fpDivId = "fp_" + buttonId;
  var existingFpDiv = dojo.byId(fpDivId);
  
  if(existingFpDiv) {
    dijit.byId(fpDivId).bringToTop();
    return;
  }
  
  if(buttonId.match("src$")) { //Show the FloatingPane with code  
    var div = dojo.doc.createElement('div');
    div.id = fpDivId;
    
    dojo.body().appendChild(div);
    var fp = new dojox.layout.FloatingPane({
      title: "Source",
      closeable:true, dockable:false, resizable: true, maxable:false,
      href:"java_code_pages/" + buttonId + ".html",
      onDownloadEnd: highlightCode
    },div);
      
    dojo.style(fp.domNode,{
      width:"500px",
      height:"300px",
      top:"280px", left:"550px",
      position:"absolute",
      zIndex:"980"
    });
    fp.startup();
    fp.show();
  } else { // Show LightBox with image
    tablesDialog.show({ leaveTitle:true,
                  href:"tables_images/" + buttonId + ".png" });
  }
}

function onTabClose(event) {
  var floatingPaneIdPrefix = "fp_" + this.id;
  // destroy all floating panes for this tab
  // get all the DOMNodes with id prefix built above
  var floatingPanes = getFloatingPanesForTab(floatingPaneIdPrefix);
  //fetch widgets for above DOMNodes and close them 
  dojo.forEach(floatingPanes, "dijit.getEnclosingWidget(item).close()");
  tabContainer.back();
  return true;
}

function getFloatingPanesForTab(paneIdPrefix) {
  return dojo.query("div[id^=" + paneIdPrefix + "]");
}

function onTabHide(event) {
  var floatingPaneIdPrefix = "fp_" + this.id;
  var floatingPanes = getFloatingPanesForTab(floatingPaneIdPrefix);
  //fetch widgets for above DOMNodes and hide them
  dojo.forEach(floatingPanes, "dijit.getEnclosingWidget(item).hide()"); 
  return true;
}

function onTabShow(event) {
  var floatingPaneIdPrefix = "fp_" + this.id;
  var floatingPanes = getFloatingPanesForTab(floatingPaneIdPrefix);
  dojo.forEach(floatingPanes, "dijit.getEnclosingWidget(item).show()");
  
  //Focus on the corresponding node in navigation tree
  var treeNode = null;
  if(this.id == "preface") {
    treeNode = getTreeNodeById(topicTree.model.root.id, true);
  } else {
    treeNode = getTreeNodeById(this.id, false);
  }
  if (treeNode) {
    topicTree.focusNode(treeNode);
  }
  return true;
}

function getTreeNodeById(id, isRoot) {
  var itemFetched = null;
  var onItemFunction = function(item) {
    itemFetched = item;
  };
  if (isRoot) {
    topicModel.fetchItemByIdentity({identity: id, onItem : onItemFunction});
  } else {
    topicStore.fetchItemByIdentity({identity: id, onItem : onItemFunction});
  }
  var nodes = topicTree.getNodesByItem(itemFetched);
  //returning 0th element since it must be only one as we are fetching by identity
  return nodes[0];
}

function focusTreeRoot() {
  var rootNode = getTreeNodeById(topicTree.model.root.id, true);
  topicTree.focusNode(rootNode);
}

function navigateTree(relativePath, id) {
  var fullPath = ['toc', 'mappings'];
  fullPath.push(relativePath);
  fullPath.push(id);
  topicTree.attr('path', fullPath);
  topicTree.focusNode(getTreeNodeById(id, false));
}

function logAnalytics(pageName) {
  _gaq.push(['_trackEvent', 'Topics', 'View', pageName]);
}